package com.sxj.corejava.code15_反射;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

/**
 * @author 石小俊
 */
public class Test03_操作构造方法 {

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class c = User.class;
        // 1.获取当前类找那个所有public修饰的构造方法
        Constructor[] constructors = c.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        System.out.println("***************************");
        // 2.获取所有构造方法,不区分修饰符
        Constructor[] declaredConstructors = c.getDeclaredConstructors();
        for (Constructor constructor : declaredConstructors) {
            System.out.println(constructor);
        }
        System.out.println("***************************");

        // 3.获取指定参数的public修饰符的构造方法
        Constructor constructor = c.getConstructor();
        System.out.println(constructor);
        constructor = c.getConstructor(Integer.class, String.class, String.class);
        System.out.println(constructor);
        // 如果不是public修饰的构造方法,则抛出异常
//        constructor = c.getConstructor(Integer.class,String.class);
//        System.out.println(constructor);
        System.out.println("***************************");

        // 4.获取指定参数的构造方法,不区分修饰符
        Constructor declaredConstructor = c.getDeclaredConstructor();
        System.out.println(declaredConstructor);
        declaredConstructor = c.getDeclaredConstructor(Integer.class);
        System.out.println(declaredConstructor);
        declaredConstructor = c.getDeclaredConstructor(Integer.class, String.class);
        System.out.println(declaredConstructor);
        declaredConstructor = c.getDeclaredConstructor(Integer.class, String.class, String.class);
        System.out.println(declaredConstructor);

        System.out.println("******************************");
        // 创建对象
        constructor = c.getConstructor();
        User user = (User) constructor.newInstance();
        System.out.println(user);
        constructor = c.getConstructor(Integer.class, String.class, String.class);
        user = (User) constructor.newInstance(1, "admin", "123456");
        System.out.println(user);

//        constructor = c.getConstructor(Integer.class);
        declaredConstructor = c.getDeclaredConstructor(Integer.class);
        declaredConstructor.setAccessible(true);
        user = (User) declaredConstructor.newInstance(1);
        System.out.println(user);


    }

}
